import axios from "axios";
import QS from "qs";
import { ElMessage } from 'element-plus'

export function request(config){
    //创建axios实例
    const instance = axios.create({
        baseURL: '/api',
        timeout: 5000,
        headers: {
            'Content-Type':'application/json;charset=utf-8'
        },
        withCredentials: true,
    })
    //axios的拦截器  对发送和接收的请求进行拦截处理 处理token
    // 请求拦截
    instance.interceptors.request.use(resquest=>{
        resquest.headers['authorization'] = localStorage.getItem('token')//请求头赋值
        return resquest;//对拦截的请求放行
    },error => {})
    //响应拦截
    instance.interceptors.response.use(response=>{
        let res = response.data
        if (res.code === 200){
            return  response;
        }
        else if (res.code === 400) {
            if (res.message) {
                ElMessage({
                    showClose: true,
                    message: res.message,
                    type: 'error',
                })
            } else {
                ElMessage({
                    showClose: true,
                    message: '服务器错误 ~0.0~ ',
                    type: 'error',
                })
            }
            return Promise.reject()
        }
        else if (res.code === 401) {//权限异常
            // Element.Message.error('权限异常 -> '+response.data.message)
            // store.dispatch('logout').then(() => {
            //     router.push("/").then(r => {})
            ElMessage({
                showClose: true,
                message: '权限异常 -> '+response.data.message,
                type: 'error',
            })
                return Promise.reject()
            // })//退出登录
        }
        return  response;
    },error => {
        ElMessage({
            showClose: true,
            message: '服务器错误 ~0.0~ ',
            type: 'error',
        })
        return Promise.reject()
    })
    return instance(config);
}